package com.asynctm.android.common.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;

import com.asynctm.android.R;

/**
 * Splash Screen
 * 
 * @author rockdrigo
 */
public class SplashScreenActivity extends Activity  {

	private static final String LOG_TAG = SplashScreenActivity.class.getSimpleName();
	
	/** Tiempo en ms durante el cual se muestra el splash screens */
	private static final long DELAY = 5000;
	
	/** Indica si la pantalla se ha tocado */
	private boolean touched;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splash_screen);
		touched = false;
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		new DelayAsyncTask().execute(new Void[]{});
	}
	
	/**
	 * Espera el tiempo definido por {@link SplashScreenActivity#DELAY}, una vez transcurrido este tiempo o si la pantalla ha sido 
	 * tocada durante el mismo se lanza la actividad de login
	 * 
	 * @author rockdrigo
	 */
	private class DelayAsyncTask extends AsyncTask<Void, Void, Void> {
		
		private long elapsedTime;
		private long INTERVAL = 100;
		
		public DelayAsyncTask() {
			this.elapsedTime = 0;
		}
		
		@Override
		protected Void doInBackground(Void... arg0) {
			while( (elapsedTime < DELAY) && (!touched) ) {
				try {
					Thread.sleep(INTERVAL);
				} catch (InterruptedException e) {
					Log.e(LOG_TAG, "Error al esperar", e);
				}
				elapsedTime = elapsedTime + INTERVAL;
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			Intent intent = new Intent(SplashScreenActivity.this, AppMenuActivity.class);
			SplashScreenActivity.this.startActivity(intent);
			SplashScreenActivity.this.finish();
		}
		
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if(event.getAction() == MotionEvent.ACTION_DOWN) {
			touched = true;
		}
		return true;
	}

}
